interface ItemType {
    title: string,
    children?: any[]
}

enum Back {
    "#ccc" = 1,
    "green",
    "red"
}

let num:number = 0

const MenuArr = (arr: ItemType[], num:number): string => {
    num += 1
    const menuStr = arr.map(item => {
        return `
            <div style="background: ${Back[num]};border-bottom:1px solid #ccc">
                <p class="btn"> ${item.title} </p>
                ${!item.children ? '' : `<div class="menuItem" style="transition: all 3s;">${MenuArr(item.children, num)}</div>`
            }
            </div>
        `
    }).join('')

    return menuStr
}

// 渲染
const render = (): void => {
    // 非空断言
    const BoxDom: Element | null = document.querySelector('.box');

    // 渲染到页面上
    (BoxDom as Element).innerHTML = MenuArr(menu, num)

    bindEvent()
}



// 给第一项添加点击事件
const bindEvent = (): void => {
    const pDom: any[] | null = Array.from(document.querySelectorAll('.btn'));

    (pDom as []).forEach(item => {
        (item as Element).addEventListener('click', (e:any) => {
            if (e.target.nextElementSibling) {
                if (e.target.nextElementSibling.style.display === 'block') {
                    e.target.nextElementSibling.style.display = 'none'
                } else {
                    e.target.nextElementSibling.style.display = 'block'
                }
                
            }
        })
    })
}

render()

